package org.glut.saltedfish.servlet;

import com.google.gson.GsonBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.glut.saltedfish.domain.ChatRecords;
import org.glut.saltedfish.domain.User;
import org.glut.saltedfish.service.ChatRecordsServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@WebServlet("/chatObject")
public class ChatObjectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json;charset=UTF-8");

        // 获取请求参数
        Integer id = null;
        if (req.getParameter("id") != null) {
            id = Integer.parseInt(req.getParameter("id"));
        }

        // 调用两个方法并合并结果
        List<ChatRecords> resultFromSI = new ChatRecordsServiceImpl().searchObjectBySI(id);
        List<ChatRecords> resultFromRI = new ChatRecordsServiceImpl().searchObjectByRI(id);

        // 合并并去重（基于自定义的聊天会话去重逻辑）
        List<ChatRecords> mergedResult = Stream.concat(resultFromSI.stream(), resultFromRI.stream())
                .filter(distinctByChatSession())
                .collect(Collectors.toList());

        // 返回 JSON 响应
        new GsonBuilder()
                .setPrettyPrinting()
                .create()
                .toJson(mergedResult, writer);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    // 自定义去重逻辑，根据 sender_id 和 receiver_id 组合去重
    private static Predicate<ChatRecords> distinctByChatSession() {
        // 将 ConcurrentHashMap 移到 Predicate 内部，确保所有元素共享同一个实例
        ConcurrentHashMap<String, Boolean> seen = new ConcurrentHashMap<>();

        return chatRecord -> {
            // 对 sender_id 和 receiver_id 排序后拼接，作为会话唯一标识
            List<Integer> ids = new ArrayList<>();
            ids.add(chatRecord.getSenderId());
            ids.add(chatRecord.getReceiverId());
            ids.sort(Comparator.naturalOrder());
            String sessionKey = ids.get(0) + "_" + ids.get(1);

            // 使用共享的 ConcurrentHashMap 记录已出现的会话标识
            return seen.putIfAbsent(sessionKey, Boolean.TRUE) == null;
        };
    }
}